'use strict';

const iosocket = require('socket.io');
const fs = require('fs');
const jv = require("libjv");
const util = require("./util");
const roomService = require("./service/RoomService")
const userService = require("./service/UserService")

let port = (process.argv.find(it => it.startsWith("-port=")) || "").split("=").last() || 3000
const io = iosocket.listen(port);
let mor = require("./lib/mongo/mor");

util.log("server listen on {0}", port)

process.on('uncaughtException', (reason, p) => {
    console.log("Unhandled Rejection at: Promise ", p, " reason: ", reason.stack);
});

io.on('connection', async function (socket) {
    // util.log(socket.id + " connected! 共有 " + Object.keys(socket.server.sockets.connected).length + " 个");

    //断开连接后，刷新房间信息和在线信息
    socket.on('disconnect', function (data) {
        if (data.Type == "string") {
            // util.log(socket.id + " disconnected. 共有 " + Object.keys(socket.server.sockets.connected).length + "  个")
            return
        }
        else {
            util.log(data);
        }
        // RoomManager.getInstance().removeNick(socket.room, socket.nick);
        // io.to(socket.room).emit('refreshRooms', RoomManager.getInstance().getRooms());
        //
        // util.log(socket.nick + " disconnect " + socket.room)
    });

    socket.on('error', (error) => {
        util.log("error: " + error);
    });

    socket.on('login', async function (data) {
        let type = data.type;
        if (type === 0) {
            let userId = data.userId;
            let [rooms, friends] = await Promise.all([
                userService.getRoomList(userId),
                userService.getFriends(userId)
            ]);
            socket.emit('login', {rooms, friends});
        }
        else {
            socket.emit('login', {rooms: await  userService.getRoomList(data.salerId)});
        }
    });

    socket.on('init-chat', async function (data) {
        let executor = [userService.getUserInfo(data.type === 0 ? data.userId : data.salerId)];

        if (data.roomId) {
            executor.push(mor.im.room.queryById(data.roomId).toEntity())
        }
        else {
            executor.push(roomService.getRoomInfo(data.salerId, data.userId))
        }

        let [user, room] = await Promise.all(executor);
        if (!room) {
            return
        }

        socket.join(room.id);
        io.to(socket.id).emit("init-chat", {room, user});
    });

    //接收到消息后，向房间内其他人广播消息
    socket.on('speech', function (data) {
        // socket.broadcast.to(data.room_id).emit('message', data);
        io.to(data.roomId).emit('message', data);
        roomService.message(data)
    });

    //单聊
    socket.on('talk', function (talkId, userId, talkUserId, content) {
        // socket.broadcast.to(data.room_id).emit('message', data);
        var room = "!" + [userId, talkUserId].sort((a, b) => a > b).join("-");
        // console.log("roomId:" + room);
        socket.join(room);
        socket.room = room;
        io.to(room).emit('message', {talkId, userId, content});
        roomService.message({talkId, type: "talk", userId, talkUserId, content});
    });
    //接收到消息后，向房间内其他人广播消息
    socket.on('status', function (data) {
        socket.broadcast.to(data.room_id).emit('message', data);
    });

    //加入房间，刷新房间信息和在线信息
    socket.on('join-room', function (data) {
        socket.join(data.room);
        io.to(data.room).emit('message', `小伙伴${data.nick} 来了(^o^) 。。。`);
        socket.room = data.room;
    });

    //离开房间，刷新房间信息和在线信息
    socket.on('leaveRoom', function (data) {
        socket.leave(data.room);
        io.to(data.room).emit('message', `${data.nick} 一路走好(T_T) 。。。`);
        socket.room = data.room;
    });

    //改变昵称，刷新在线信息
    socket.on('changeNick', function (data) {
        io.to(data.room).emit('message', `小伙伴${data.nickOld}神奇的变成了${data.nickNew}(⊙o⊙)。。。`);
        socket.room = data.room;
    });

    // socket.on("ajax",function(id,url,data){
    //     debugger;
    //     console.log(id);
    //     console.log(url);
    //     console.log(data);
    //     var cookie = (socket.request.headers.cookie.split(";").filter(it=>it.includes("JSESSIONID="))[0] || "").split("=").last().trim();
    //
    //     if( url == "/loginInfo/getMine"){
    //         socket.emit('ajax',id, );
    //     }
    // });

    //socket连上之后，刷新房间信息
    // socket.emit('refreshRooms', RoomManager.getInstance().getRooms());

    let [users, salers] = await Promise.all([
        mor.sys.user.query().where({type: 0}).toList(),
        mor.sys.user.query().where({type: 1}).toList()
    ]);

    socket.emit('dev-users', users);
    socket.emit('dev-salers', salers);
});
